package practica2;

import java.util.Random;

import weka.classifiers.Evaluation;
import weka.classifiers.lazy.IBk;
import weka.core.ChebyshevDistance;
import weka.core.EuclideanDistance;
import weka.core.Instances;
import weka.core.ManhattanDistance;
import weka.core.SelectedTag;
import weka.core.neighboursearch.LinearNNSearch;

/**
 * 3. CLASSIFY
 *  
 * @author luciarodero
 */
public class Classify {
	
	public Classify(){}

	public void classifier(Instances data) throws Exception{
		double fMeasure = 0;
		int bestW = 0;
		int bestD = 0;
		int bestK = 0;
		double fm = 0.0;
			
		for(int i = 1; i <= 10; i++) { //k
			IBk estimador = new IBk(i);

			for(int j = 1; j <= 3; j++) { //Weight
				if(j == 1) 
					estimador.setDistanceWeighting(new SelectedTag(IBk.WEIGHT_INVERSE, IBk.TAGS_WEIGHTING));
				else if(j == 2) 
					estimador.setDistanceWeighting(new SelectedTag(IBk.WEIGHT_SIMILARITY, IBk.TAGS_WEIGHTING));	
				else 
					estimador.setDistanceWeighting(new SelectedTag(IBk.WEIGHT_NONE, IBk.TAGS_WEIGHTING));
					
				for(int z = 1; z <= 3; z++){ //Distance
					LinearNNSearch lnns = new LinearNNSearch();
						
					if(z == 1) lnns.setDistanceFunction(new EuclideanDistance());
					else if(z == 2) lnns.setDistanceFunction(new ManhattanDistance());
					else lnns.setDistanceFunction(new ChebyshevDistance());
						
					estimador.setNearestNeighbourSearchAlgorithm(lnns);
					Evaluation evaluator = new Evaluation(data);
					evaluator.crossValidateModel(estimador, data, 10, new Random(1)); //10-fold Cross Validation
					fm = evaluator.weightedFMeasure(); //f-measure
						
					if(fm > fMeasure) { //Save best: f-measure, k, distance and weight
						bestK = i;
						fMeasure = fm;
						bestD = z;
						bestW = j;
					}
				}
			}
		}
		
		ShowResults sr = new ShowResults();
		sr.print(bestW, bestD, bestK, fMeasure);
	}
}
